package com.icinfo.cloud.provider.punish.ucase.punishinform.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.peripheralinterface.lawenforce.dto.CaseBaseInfoSaveDto;
import com.icinfo.cloud.provider.punish.api.enums.TransferEvidenceFileTypeEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseAttachmentInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordCriminalDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.AttachmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseAppendixRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseAttachmentInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.criminaltransfer.service.ICaseCriminalTransferFileService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.CaseCriminalTransferFileSaveDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.CriminalCaseTransferQueryDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.CriminalCaseTransferSaveDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.service.ICaseCriminalTransferService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCriminalTransferFileVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCriminalTransferInfoVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述:  涉刑移送 对应的Service接口实现类.<br>
 *
 * @author shishengyao
 * @description
 * @date 2022/9/27
 */
@Service
@Transactional(rollbackFor = {Error.class, Exception.class})
@Slf4j
public class CaseCriminalTransferServiceImpl implements ICaseCriminalTransferService {
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseCriminalTransferFileService caseCriminalTransferFileService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    private static  final String IMAGE_FILE_TYPE="jpg,jpeg,png,bmp,gif";

    @Override
    public CaseCriminalTransferInfoVo getCriminalCaseTransferInfo(CriminalCaseTransferQueryDto queryDto) {
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(queryDto.getCaseId());
        CaseCriminalTransferInfoVo caseTransferInfoVo = new CaseCriminalTransferInfoVo();
        caseTransferInfoVo.setCriminalCaseReason(caseMainDetailInfo.getCriminalCaseReason());
        caseTransferInfoVo.setCriminalCaseTransferDeptCode(caseMainDetailInfo.getCriminalCaseTransferDeptCode());
        caseTransferInfoVo.setCriminalCaseTransferDeptName(caseMainDetailInfo.getCriminalCaseTransferDeptName());
        List<CaseCriminalTransferFileVo> fileList = new ArrayList<>();
        if (ObjectUtil.isEmpty(caseMainDetailInfo.getCriminalCaseTransferDeptCode())) {
            //案件调查报告
            List<CaseDocumentRecordDto> zjbgList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(queryDto.getCaseId(), DocumentKindEnum.DOC_KIND_ZJBG.getCode());
            if (ObjectUtils.isEmpty(zjbgList)) {
                throw new BusinessException("案件调查报告不存在！");
            }
            List<CaseCriminalTransferFileVo> finalFileList = fileList;
            zjbgList.forEach(e -> {
                CaseCriminalTransferFileVo fileInfoDto = new CaseCriminalTransferFileVo();
                fileInfoDto.setId(e.getId());
                fileInfoDto.setUploadUserName(e.getCreateUserName());
                fileInfoDto.setUploadUserId(e.getCreateUserId());
                fileInfoDto.setUploadTime(e.getDocumentCreateTime());
                fileInfoDto.setFileOwnId(e.getId());
                fileInfoDto.setFileType("pdf");
                fileInfoDto.setEvidenceFileType("WJ");
                fileInfoDto.setFileSource("4");
                fileInfoDto.setFileUrl(e.getDocumentUrl());
                if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSeal())) {
                    fileInfoDto.setFileUrl(e.getDocumentUrlAfterSeal());
                }
                if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSign())) {
                    fileInfoDto.setFileUrl(e.getDocumentUrlAfterSign());
                }
                //签字确认取线下上传文书
                if (DocumentStatusEnum.CONFIRM_END.getCode().equals(e.getDocumentSignstampedStatus()) && StringUtils.isEmpty(e.getDocumentUrlAfterSign())){
                    Example example = new Example(CaseAppendixRecord.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("caseId", queryDto.getCaseId()).andEqualTo("documentCatalogCode", e.getDocumentCatalogCode()).andEqualTo("appendixTypeId", "SIGN_ATTACHMENT");
                    List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(example);
                    if (ObjectUtil.isNotEmpty(caseAppendixRecords) && caseAppendixRecords.size()>0){
                        CaseAppendixRecord  caseAppendixRecord = caseAppendixRecords.get(0);
                        fileInfoDto.setFileType(caseAppendixRecord.getAppendixNameSuffix());
                        fileInfoDto.setEvidenceFileType("WJ");
                        if (IMAGE_FILE_TYPE.contains(caseAppendixRecord.getAppendixNameSuffix())){
                            fileInfoDto.setEvidenceFileType("TP");
                        }
                        fileInfoDto.setFileUrl(caseAppendixRecord.getAppendixUrl());
                    }
                }
                fileInfoDto.setTransferFileSource(Constant.STRING_1);
                fileInfoDto.setFileName(e.getDocumentKindName());
                fileInfoDto.setIsDisable(Constant.STRING_1);
                finalFileList.add(fileInfoDto);
            });
            fileList = finalFileList;
        } else {
            //1、查询移送文件
            fileList = caseCriminalTransferFileService.getCaseCriminalTransferFileListByCaseId(queryDto.getCaseId());
            fileList.forEach(e -> {
                if ("ZJBG".equals(e.getEvidenceType())) {
                    e.setIsDisable(Constant.STRING_1);
                }
            });

            //2、查询附件信息
            CaseAttachmentInfoQueryDto attachmentInfoQueryDto = new CaseAttachmentInfoQueryDto();
            attachmentInfoQueryDto.setCaseId(queryDto.getCaseId());
            attachmentInfoQueryDto.setDocumentCatalogCode(queryDto.getDocumentCatalogCode());
            List<CaseAttachmentInfoVo> caseAttachmentList = caseAppendixRecordService.getCaseAttachmentList(attachmentInfoQueryDto);
            caseTransferInfoVo.setAttachmentInfoVoList(caseAttachmentList);
        }
        caseTransferInfoVo.setCriminalCaseTransferFile(fileList);
        return caseTransferInfoVo;
    }

    @Override
    public int saveCriminalCaseTransfer(CriminalCaseTransferSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        String caseId = saveDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(saveDto.getCaseId());
        String documentCatalogCode = saveDto.getDocumentCatalogCode();

        // todo 处理结论；0 行政处罚,1 涉刑移送  不是涉刑移送不可保存移送信息
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        if (!Constant.STRING_1.equals(caseMainDetailInfo.getHandleConclusion())) {
            throw new BusinessException("案件结论不是涉刑移送，不可移送");
        }
        //1、 保存移送材料信息
        List<CaseCriminalTransferFileSaveDto> criminalCaseTransferFile = saveDto.getCriminalCaseTransferFile();
        caseCriminalTransferFileService.saveCaseCriminalTransferFile(caseId, criminalCaseTransferFile);

        //2、保存附件信息
        caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCode(saveDto.getCaseId(), documentCatalogCode);
        List<CaseAttachmentInfoVo> appendixList = saveDto.getAttachmentInfoVoList();
        if (ObjectUtil.isNotEmpty(appendixList) && appendixList.size()>0){
            for (CaseAttachmentInfoVo appendixDto : appendixList) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                record.setCaseId(caseId);
                record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                record.setAppendixUrl(appendixDto.getAppendixUrl());
                record.setAppendixTypeId(appendixDto.getAppendixTypeId());
                record.setAppendixName(appendixDto.getAppendixName());
                record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                record.setDocumentCatalogCode(documentCatalogCode);
                record.setUploadUserId(userInfo.getUserId() + "");
                record.setUploadUserName(userInfo.getRealName());
                record.setUploadTime(LocalDateTime.now());
                caseAppendixRecordService.saveCaseAppendixRecord(record);
            }
        }

        //3、更新涉刑移送表单数据
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(saveDto.getCaseId());
        updateCaseMainDetailInfo.setCriminalCaseReason(saveDto.getCriminalCaseReason());
        updateCaseMainDetailInfo.setCriminalCaseReasonName(saveDto.getCriminalCaseReasonName());
        updateCaseMainDetailInfo.setCriminalCaseTransferDeptCode(saveDto.getCriminalCaseTransferDeptCode());
        updateCaseMainDetailInfo.setCriminalCaseTransferDeptName(saveDto.getCriminalCaseTransferDeptName());
        return caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }

    /**
     * 更新移送证据及移送文书号
     *
     * @param caseBaseInfoDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCaseMainDetailInfoCriminal(CaseBaseInfoSaveDto caseBaseInfoDto) {
        //保存移送材料信息
        caseCriminalTransferFileService.saveCaseCriminalTransferFileNew(caseBaseInfoDto.getCaseBaseId(), caseBaseInfoDto.getEvidenceInfoDtoList());

        //更新涉刑移送表单数据
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(caseBaseInfoDto.getCaseBaseId());
        updateCaseMainDetailInfo.setCriminalCaseReason(caseBaseInfoDto.getAy());
        //updateCaseMainDetailInfo.setCriminalCaseReasonName(saveDto.getCriminalCaseReasonName());
        updateCaseMainDetailInfo.setCriminalCaseTransferDeptCode(caseBaseInfoDto.getSwdw());
        updateCaseMainDetailInfo.setCriminalCaseTransferDeptName(caseBaseInfoDto.getSwdwmc());
        return caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }


    @Override
    public List<CaseCriminalTransferFileVo> getCriminalCaseTransferDocumentList(CriminalCaseTransferQueryDto queryDto) {
        String caseId = queryDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        // 1、获取文书
        List<CaseDocumentRecordCriminalDto> materialVoList;

        //type=1，查询案件移交文书列表
        if (StringUtils.isNotBlank(queryDto.getType())) {
            materialVoList = caseDocumentRecordService.getTransferDocumentRecordOfCriminal(caseId);
        } else {
            materialVoList = caseDocumentRecordService.getDocumentRecordOfCriminal(caseId);
        }

        List<CaseCriminalTransferFileVo> caseDocumentRecordVos = new ArrayList<>();
        materialVoList.forEach(e -> {
            CaseCriminalTransferFileVo vo = new CaseCriminalTransferFileVo();
            BeanUtils.copyProperties(e, vo);
            vo.setId(e.getId());
            vo.setUploadUserName(e.getCreateUserName());
            vo.setUploadUserId(e.getCreateUserId());
            vo.setUploadTime(e.getDocumentCreateTime());
            vo.setFileOwnId(e.getId());
            vo.setFileType("pdf");
            vo.setEvidenceFileType("WJ");
            vo.setFileSource("4");
            vo.setFileUrl( e.getDocumentUrl());
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSeal())) {
                vo.setFileUrl(e.getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSign())) {
                vo.setFileUrl(e.getDocumentUrlAfterSign());
            }
            //签字确认取线下上传文书
            if (DocumentStatusEnum.CONFIRM_END.getCode().equals(e.getDocumentSignstampedStatus()) && StringUtils.isEmpty(e.getDocumentUrlAfterSign())){
                Example example = new Example(CaseAppendixRecord.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("caseId", queryDto.getCaseId()).andEqualTo("documentCatalogCode", e.getDocumentCatalogCode()).andEqualTo("appendixTypeId", AttachmentTypeEnum.OFFLINE_SIGN_FILE.getCode());
                List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(example);
                if (ObjectUtil.isNotEmpty(caseAppendixRecords) && caseAppendixRecords.size()>0){
                    CaseAppendixRecord  caseAppendixRecord = caseAppendixRecords.get(0);
                    vo.setFileType(caseAppendixRecord.getAppendixNameSuffix());
                    vo.setEvidenceFileType("WJ");
                    if (IMAGE_FILE_TYPE.contains(caseAppendixRecord.getAppendixNameSuffix())){
                        vo.setEvidenceFileType("TP");
                    }
                    vo.setFileUrl(caseAppendixRecord.getAppendixUrl());
                }
            }
            vo.setTransferFileSource(Constant.STRING_1);
            vo.setFileName(e.getDocumentCatalogName());
            if (Constant.STRING_2.equals(e.getDocumentLinkObjectType())
                    && PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())
                    && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
                vo.setFileName(e.getDocumentCatalogName() + "(" + e.getPartyName() + ")");
            }
            if (DocumentKindEnum.DOC_KIND_ZJBG.getCode().equals(e.getDocumentKindCode())) {
                vo.setIsDisable(Constant.STRING_1);
            }
            vo.setLabel(vo.getFileName());
            caseDocumentRecordVos.add(vo);
        });
        return caseDocumentRecordVos;
    }

    /**
     * 描述： 根据caseId获取证据列表
     *
     * @param queryDto 查询dto
     * @return {@link List< CaseCriminalTransferFileVo > }
     * @author shishengyao
     * @date 2022/10/10
     */
    @Override
    public List<CaseCriminalTransferFileVo> getCriminalCaseTransferEvidenceList(CriminalCaseTransferQueryDto queryDto) {
        String caseId = queryDto.getCaseId();
        List<Map> evidenceDetailList = evidenceInventoryService.getEvidenceDetailList(caseId);
        List<CaseCriminalTransferFileVo> transferFileVoList = caseCriminalTransferFileService.getCaseCriminalTransferFileListByCaseId(caseId);
        String transferFileIds = transferFileVoList.stream().filter(e -> Constant.STRING_2.equals(e.getTransferFileSource()))
                .map(e -> e.getFileOwnId()).collect(Collectors.joining(","));
        List<CaseCriminalTransferFileVo> criminalTransferFileVoList = new ArrayList<>();

        if (ObjectUtil.isNotEmpty(evidenceDetailList)) {
            for (Map evidenceDetail : evidenceDetailList) {
                /*if (ObjectUtil.isNotEmpty(evidenceDetail.get("pdfUrl"))) {
                    transferFileVo.setFileOwnId(evidenceDetail.get("uid").toString());
                    transferFileVo.setId(evidenceDetail.get("uid").toString());
                    transferFileVo.setLabel(evidenceDetail.get("evidenceName").toString());
                    transferFileVo.setTransferFileSource(Constant.STRING_2);
                    transferFileVo.setFileUrl(evidenceDetail.get("pdfUrl").toString());
                    transferFileVo.setFileName(evidenceDetail.get("evidenceName").toString());
                    transferFileVo.setEvidenceTypeName("现场照片等音像记录证据");
                    transferFileVo.setEvidenceType("04010004");
                    transferFileVo.setFileOwnType("04010004");
                    transferFileVo.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
                    transferFileVo.setFileType("pdf");
                    transferFileVo.setFileSource("4");
                } else {*/
                //修改为全部取证据文件信息
                if (ObjectUtil.isNotEmpty(evidenceDetail.get("evidenceFileList"))) {
                    List<Map> evidenceFileList = JSON.parseArray(JSON.toJSONString(evidenceDetail.get("evidenceFileList")), Map.class);
                    for (Map evidenceFile : evidenceFileList) {
                        //证据名称+"-"+文件名称
                        String fileName = evidenceDetail.get("evidenceName").toString() + "-" + evidenceFile.get("fileName").toString();
                        CaseCriminalTransferFileVo transferFileVo = new CaseCriminalTransferFileVo();
                        if (transferFileIds.contains(evidenceFile.get("uid").toString())) {
                            transferFileVo.setIsSelected(Constant.STRING_1);
                        } else {
                            transferFileVo.setIsSelected(Constant.STRING_0);
                        }

                        transferFileVo.setFileOwnId(evidenceFile.get("uid").toString());
                        transferFileVo.setId(evidenceFile.get("uid").toString());
                        transferFileVo.setLabel(fileName);
                        transferFileVo.setTransferFileSource(Constant.STRING_2);
                        transferFileVo.setFileUrl(evidenceFile.get("fileUrl").toString());
                        transferFileVo.setFileName(fileName);
                        transferFileVo.setEvidenceTypeName("现场照片等音像记录证据");
                        transferFileVo.setEvidenceType("04010004");
                        transferFileVo.setFileOwnType("04010004");
                        if (YesOrNoEnum.YES.getCode().equals(evidenceFile.get("isImage").toString())) {
                            transferFileVo.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
                        } else {
                            transferFileVo.setEvidenceFileType(TransferEvidenceFileTypeEnum.FILE.getCode());
                        }
                        transferFileVo.setFileType(evidenceFile.get("fileSuffix").toString());
                        transferFileVo.setFileSource("4");

                        criminalTransferFileVoList.add(transferFileVo);
                    }

                }
                //}



                //              List<CaseCriminalTransferFileVo> childrenList = new ArrayList<>();
//                if (ObjectUtil.isNotEmpty(evidenceDetail.get("evidenceFileList"))) {
//                    List<Map> evidenceFileList = JSON.parseArray(JSON.toJSONString(evidenceDetail.get("evidenceFileList")), Map.class);
//                    for (Map evidenceFile : evidenceFileList) {
//                        CaseCriminalTransferFileVo children = new CaseCriminalTransferFileVo();
//                        String uid = evidenceFile.get("uid").toString();
//                        children.setFileOwnId(uid);
//                        children.setId(uid);
//                        children.setLabel(evidenceFile.get("fileName").toString());
//                        children.setTransferFileSource(Constant.STRING_2);
//                        children.setFileUrl(evidenceFile.get("fileUrl").toString());
//                        children.setFileName(evidenceFile.get("fileName").toString());
//                        children.setEvidenceTypeName("现场照片等音像记录证据");
//                        children.setEvidenceType("04010004");
//                        children.setEvidenceFileType("WJ");
//                        children.setFileOwnType("");
//                        children.setFileSource("4");
//                        children.setFileType(evidenceFile.get("fileSuffix").toString());
//                        children.setFileSize(evidenceFile.get("fileSize").toString());
//                        childrenList.add(children);
//                    }
//                }
                //              transferFileVo.setChildren(childrenList);
                //criminalTransferFileVoList.add(transferFileVo);

            }
        }
        return criminalTransferFileVoList;
    }
}
